import { history } from 'umi';
import request from 'umi-request';
import { message } from 'antd';
import { getAuthRoutes, getActualPath } from '@/utils/auth/helper';
import pageTabUtil from '@/utils/pageTabUtil';
import moment from 'moment';
import { trackSessionID } from '@/utils/track';
// import { parseLocation } from '@/utils/utils';

// 生成会话id，用于埋点
trackSessionID();

const ERROR_MSG_KEY = 'errorMsg';

// 每次路由更改，都需要去请求目前最新的时间戳，如果判断不一致需要刷新页面。。。
const matchTime = async () => {
    const result = await request.get('/__time__.json', {
        useCache: false,
        requestType: 'json',
        responseType: 'json'
    });
    const time = parseInt(localStorage.getItem('__time__'), 10);

    if (result && result.time && time !== result.time) {
        localStorage.setItem('__time__', result.time);
        // eslint-disable-next-line no-restricted-globals
        location.reload();
    }
};

const checkStatic = (routes, pathname) => routes.some(item => item.static && pathname.indexOf(item.path) === 0);

const handleNoAuth = rootPath => {
    pageTabUtil.clearAllTabHistory();
    sessionStorage.setItem(ERROR_MSG_KEY, '系统冲突！检测到无对应权限，请确认权限配置！');
    history.push({
        pathname: rootPath,
        state: { tabRoute: true }
    });
};

// once
export async function patchRoutes({ routes }) {
    const { pathname } = window.location;
    const isStatic = checkStatic(routes, pathname);
    if (isStatic) return;
    const isLogin = localStorage.getItem('user');
    // 如果没有登录，不做处理
    if (!isLogin) return;

    // 如果已经登录，则直接跳转到首页
    if (pathname.includes('/user/login')) {
        history.push('/');
    }
}

export async function onRouteChange({ location, routes }) {
    if (process.env.NODE_ENV === 'production') {
        await matchTime();
    }
    const { pathname } = location;

    // 埋点 记录页面信息
    const pageTrack = JSON.parse(localStorage.getItem('pageTrack') || '{}');

    // 临时排除邮件详情
    if (pathname !== '/personal/message/mails/mailInfo') {
        localStorage.setItem(
            'pageTrack',
            JSON.stringify({
                url: window.location.href,
                pageName: document.title,
                lastPageName: pageTrack.pageName,
                lastPageUrl: pageTrack.url,
                enterTime: moment().format('YYYY-MM-DD hh:mm:ss')
            })
        );
    }

    const isStatic = checkStatic(routes, pathname);
    if (isStatic) return;
    const isLogin = localStorage.getItem('user');
    // 如果没有登录，不做处理
    if (!isLogin) return;

    if (pathname.indexOf('/user') === 0) return;

    // 如果没有权限菜单，请求
    const mainRoutes = routes.find(item => item.path === '/').routes; // 只需要部分路由

    const { tmpRoutes, flatterMenu } = await getAuthRoutes(mainRoutes);

    if (!tmpRoutes?.length) return;

    const homeRoute = tmpRoutes.find(item => !item.disabled);

    const targetRoute = flatterMenu[pathname];
    if (!targetRoute && pathname !== '/') {
        console.error(pathname, '===无权限路由===');
        handleNoAuth(homeRoute.path);
        return;
    }

    // 获取菜单后判断是否有登录定向的地址！！好像，只能在这里添加了
    // let loginRedirect = sessionStorage.getItem('loginRedirect');
    // if (loginRedirect && loginRedirect !== 'undefined') {
    //     loginRedirect = decodeURI(loginRedirect);
    //     sessionStorage.removeItem('loginRedirect');
    //     const [redirectUrl, redirectQuery] = parseLocation({ pathname: loginRedirect });
    //     history.push({ pathname: redirectUrl, query: redirectQuery, state: { tabRoute: true, tabRefresh: true } });
    //     return;
    // }

    if (pathname === '/') {
        history.push(homeRoute.path);
        return;
    }

    if (!targetRoute.component) {
        const redirectPath = getActualPath(pathname);
        if (redirectPath) {
            history.push({
                pathname: redirectPath,
                state: { tabRoute: true }
            });
            return;
        }
        console.error(pathname, '===无权限路由===');
        handleNoAuth(homeRoute.path);
        return;
    }

    const msg = sessionStorage.getItem(ERROR_MSG_KEY);
    if (msg) {
        message.error(msg, 5);
        sessionStorage.removeItem(ERROR_MSG_KEY);
    }
}
